package tech.mhuang.pacebox.sms.tencent;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import tech.mhuang.pacebox.core.exception.ExceptionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.sms.BaseSmsHandler;
import tech.mhuang.pacebox.sms.SmsFieldProperties;
import tech.mhuang.pacebox.sms.domain.SmsSendRequest;
import tech.mhuang.pacebox.sms.domain.SmsSendResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 腾讯云短信调用
 *
 * @author mhuang
 * @since 1.0.0
 */
public class TencentSmsHandler implements BaseSmsHandler {

    private SmsFieldProperties properties;

    private SmsClient client;

    @Override
    public void setFieldProperties(SmsFieldProperties properties) {
        this.properties = properties;
        Credential credential = new Credential(properties.getAccessKey(), properties.getAccessSecret());
        ClientProfile clientProfile = new ClientProfile();
        HttpProfile httpProfile = clientProfile.getHttpProfile();
        httpProfile.setEndpoint(properties.getRegion());
        httpProfile.setReqMethod("POST");
        if (properties.isUseProxy()) {
            httpProfile.setProxyHost(properties.getProxyHost());
            httpProfile.setProxyPort(properties.getProxyPort());
        }
        this.client = new SmsClient(credential, "", clientProfile);
    }

    @Override
    public SmsSendResult send(SmsSendRequest smsSendRequest) {
        SmsSendResult smsResult = SmsSendResult.builder().extendParam(smsSendRequest.getExtendParam()).build();
        SendSmsRequest request = new SendSmsRequest();
        request.setSmsSdkAppid(smsSendRequest.getAppId());
        request.setTemplateID(smsSendRequest.getTemplateCode());
        request.setSign(smsSendRequest.getSign());
        String[] mobile = StringUtil.split(smsSendRequest.getMobile(), ",");
        request.setPhoneNumberSet(mobile);
        Set<String> keys = smsSendRequest.getTemplateParam().keySet();
        List<String> templateParam = new ArrayList<>(keys.size());
        for (String key : keys) {
            templateParam.add(smsSendRequest.getTemplateParam().get(key, String.class));
        }
        request.setTemplateParamSet(templateParam.toArray(new String[templateParam.size()]));
        try {
            SendSmsResponse res = client.SendSms(request);
            smsResult.setSuccess(true);
            smsResult.setRequestId(res.getRequestId());
        } catch (TencentCloudSDKException e) {
            smsResult.setMessage(ExceptionUtil.getMessage(e));
            smsResult.setThrowable(e);
        }
        return smsResult;
    }
}
